// featurePackage/pages/eyeLove/eyeLove.js
import {
  createAppointRecord,
  queryShopList
} from '../../../service/jb_home_service'
import {

  queryShareQrCode
} from "../../../service/jb_common_service"
import {
  queryUserInfo
} from "../../../service/jb_mine_service"
import { loginWxAction } from "../../../service/config"
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    formData: {
      name: "",
      phone: '',
      num: 1,
      storeName: "",
      storeId: "",
      introPhone: "",
      introName: '',
      introUserId: "",
      visitTime: "",
    },
    storeList: [],
    showYYPop: false,
    customActionStyle: {},
    posterInfo: {

    },
    isShowSharePop: false,
    isShowPosterPop: false,
    posterImg: "",
    posterData: {
      "width": "650rpx",
      "height": "1050rpx",
      "background": "transparent",
      "views": [

      ]
    },
    posterViews: [
      //背景
      {
        "type": "image",
        "url": "https://images.jiabao19.com/common/whitebg.png",
        "css": {
          "width": "650rpx",
          "height": "1050rpx",
          "top": "0rpx",
          "left": "0rpx",
          "rotate": "0",
          "borderRadius": "",
          "borderWidth": "",
          "shadow": "",
          "mode": ""
        }
      },
      // 头像
      // {
      //   "type": "image",
      //   "url": "",
      //   "css": {
      //     "width": "80rpx",
      //     "height": "80rpx",
      //     "top": "50rpx",
      //     "left": "30rpx",
      //     "rotate": "0",
      //     "borderRadius": "40rpx",
      //     "borderWidth": "",
      //     "borderColor": "#000000",
      //     "shadow": "",
      //     "mode": "aspectFill"
      //   }

      // },
      //昵称:
      // {
      //   "type": "text",
      //   "text": "",
      //   "css": {
      //     top: "50rpx",
      //     left: "130rpx",
      //     textAlign: 'center',
      //     padding: '10rpx',
      //     scalable: true,
      //     deletable: true,
      //     "fontSize": "30rpx",
      //     "fontWeight": "bold",
      //     "color": "#333333",
      //   }
      // },
      //标语:
      // {
      //   "type": "text",
      //   "text": "嗨！给你推荐一个好物，快来看看吧！",
      //   "css": {
      //     top: "90rpx",
      //     left: "130rpx",
      //     textAlign: 'center',
      //     padding: '10rpx',
      //     scalable: true,
      //     deletable: true,
      //     "fontSize": "26rpx",
      //     "fontWeight": "normal",
      //     "color": "#b9b9b9",
      //   }
      // },
      //封面
      {
        "type": "image",
        "url": "",
        "css": {
          "width": "650rpx",
          "height": "850rpx",
          "top": "0rpx",
          "left": "0rpx",
          "rotate": "0",
          "borderWidth": "",
          "borderColor": "#000000",
          "shadow": "",
          "borderRadius": "10rpx",
          "mode": "aspectFill"
        }

      },
      //价格单位:
      {
        "type": "text",
        "text": "",
        "css": {
          top: "700rpx",
          left: "30rpx",
          textAlign: 'center',
          padding: '10rpx',
          scalable: true,
          deletable: true,
          "fontSize": "28rpx",
          "color": "#ff0000",
        }
      },
      // 价格
      {
        "type": "text",
        "text": "",
        "css": {
          top: "680rpx",
          left: "120rpx",
          textAlign: 'center',
          padding: '10rpx',
          scalable: true,
          deletable: true,
          "fontSize": "45rpx",
          "fontWeight": "bold",
          "color": "#ff0000",
        }
      },
      //二维码
      {
        "type": "image",
        "url": "",
        "css": {
          "width": "120rpx",
          "height": "120rpx",
          "top": "880rpx",
          "right": "50rpx",
          "rotate": "0",
          "borderWidth": "",
          "borderColor": "#000000",
          "shadow": "",
          "mode": "aspectFill"
        }

      },
      //二维码提示:
      {
        "type": "text",
        "text": "长按预约活动",
        "css": {
          top: "1005rpx",
          right: "30rpx",
          textAlign: 'center',
          padding: '10rpx',
          scalable: true,
          deletable: true,
          "fontSize": "26rpx",
          "fontWeight": "normal",
          "color": "#999999",
        }
      },
      //商品名称1
      {
        "type": "text",
        "text": "",
        "css": {
          // top: "780rpx",
          top: "880rpx",

          left: "30rpx",
          textAlign: 'center',
          padding: '10rpx',
          scalable: true,
          deletable: true,
          "fontSize": "30rpx",
          "fontWeight": "bold",
          "color": "#3f79dc",
        }
      },
      //商品名称2
      {
        "type": "text",
        "text": "",
        "css": {
          // top: "820rpx",
          top: "920rpx",
          left: "30rpx",
          textAlign: 'center',
          padding: '10rpx',
          scalable: true,
          deletable: true,
          "fontSize": "30rpx",
          "fontWeight": "bold",
          "color": "#3f79dc",
        }
      },
      //地址
      {
        "type": "text",
        "text": "",
        "css": {
          // top: "820rpx",
          top: "1005rpx",
          left: "30rpx",
          textAlign: 'center',
          padding: '10rpx',
          scalable: true,
          deletable: true,
          "fontSize": "24rpx",
          "fontWeight": "normal",
          "color": "#999999",
        }
      },
    ],
    productQrCode: "",//商品分享二维码
    isQueryUserInfo: false,
    shareUserId: '',
    isLogin: false,
    showLiveTimePop: false,
    maxDate: "",
    minDate: "",
    maxDate: new Date(2026, 12, 31).getTime(),
    minDate: new Date(2024, 7, 18).getTime(),
    introName: "暂无",
    introPhone: '',
    introUserId: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.queryShopList();
    // 个人信息赋值
    if (app.globalData.userInfo && app.globalData.userInfo.nickname) {
      this.setData({
        userInfo: app.globalData.userInfo
      })
    } else {
      this.setData({
        isQueryUserInfo: true,
      })
    }
    if (options.isShare) {
      this.setData({
        introPhone: options.userId,
        isShare: true,
        introUserId: options.houseNumber
      })
      // wx.setStorageSync(BIND_USER_ID, options.userId);
      this.userWxLogin();

      return;
    }
    //扫码进来的
    if (options.scene) {
      let scene = decodeURIComponent(options.scene)
      console.log("JJLog:扫码结果是==========:" + scene);
      let sceneArray = scene.split("=");
      let pStr = sceneArray[0];
      let bindStr = sceneArray[1]
      let pArr = pStr.split("&");
      let bindArr = bindStr.split("&");
      let houseNumber = pArr[1];
      let bindUserId = bindArr[1];
      console.log("JJLog:扫码进入的带看人手机号:" + houseNumber);
      console.log("JJLog:扫码进入带看人id是:" + bindUserId);


      this.setData({
        introPhone: houseNumber,
        isShare: true,
        introUserId: bindUserId
      })

      this.userWxLogin();

      return;
    }
    this.userWxLogin();
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  //用户登陆授权等:
  userWxLogin() {
    loginWxAction().then((res => {
      console.log("JJLog:登录返回:" + JSON.stringify(res));
      let data = res.data;
      if (res.code == 200) {
        app.globalData.nickName = data.nickName;
        app.globalData.avatar = data.avatar;
        app.globalData.phone = data.phone || "";
        app.globalData.isLogin = data.isLogin;
        app.globalData.openId = data.token;
        this.setData({
          shareUserId: data.uid,
          isLogin: data.isLogin
        })
        //绑定挂级关系:
        // if (this.data.bindUserId) {
        //   this.bindUserRelation();
        // }
        if (!this.data.isQueryUserInfo) {
          this.queryShareQrCode()
        }

        if (this.data.isQueryUserInfo && app.globalData.isLogin) {
          this.queryUserInfo();
        }
      }
    })).catch(err => {
      console.error("JJLog:userWxLogin", err);
    })
  },
  timePopHidden() {
    this.setData({
      showLiveTimePop: false,
    })
  },
  selectTimeAction() {
    this.setData({
      showLiveTimePop: true
    })
  },
  deliveryTimeSure(e) {
    console.log("JJLog:时间是:" + JSON.stringify(e));
    this.setData({
      'formData.visitTime': e.detail.timeStr,
    })
    this.timePopHidden();
  },

  cellInputChange(e) {
    let value = e.detail.value;
    let key = e.currentTarget.dataset.key;
    if (key == 'name') {
      this.setData({
        'formData.name': value,
      })
    }
    if (key == 'phone') {
      this.setData({
        'formData.phone': value,
      })
    }
  },
  //获取个人信息api
  queryUserInfo() {
    queryUserInfo().then(res => {
      if (res.code == 200) {
        this.setData({
          userInfo: res.data,
        })

        app.globalData.userInfo = res.data
        this.queryShareQrCode();
      }
    }).catch(err => {
      console.error("JJLog:queryUserInfo", err);
    })
  },
  queryShareQrCode() {
    let data = {
      params: {
        u: this.data.shareUserId || '111',//个人userId,
        h: this.data.userInfo.phone || '19989898989',//分享人电话
      },
      page: "featurePackage/pages/eyeLove/eyeLove"
    }
    queryShareQrCode(data).then(res => {
      console.log("JJLog:获取到的商品二维码是====:" + JSON.stringify(res));
      if (res.code == 200) {
        this.setData({
          productQrCode: res.data.code || ""
        })
      }

    }).catch(err => {

    })
  },
  selectStoreAction(e) {
    let item = e.currentTarget.dataset.item;
    this.setData({
      'formData.storeId': item.id,
      'formData.storeName': item.storeName
    })
  },

  //查询门店列表
  queryShopList() {
    wx.showLoading();
    queryShopList().then(res => {
      wx.hideLoading();
      if (res.code == 200) {
        // let obj = {
        //   storeName: "佳宝视力防控养护中心铁建广场店",
        //   storeAddress: "成都佳宝视力防控养护中心铁建广场店",
        // }
        this.setData({
          storeList: res.data || []
        })
        if (res.data && res.data.length > 0) {
          this.setData({
            'formData.storeId': res.data[0].id,
            'formData.storeName': res.data[0].storeName
          })
        }
      }
    }).catch(err => {
      wx.hideLoading();
    })
  },
  //点击确认预约按钮
  sureAppointAction() {
    if (!this.data.formData.name) {
      wx.showToast({
        title: '请输入姓名',
        icon: "none"
      })
      return
    }

    if (!this.data.formData.phone || this.data.formData.phone.length != 11) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: "none"
      })
      return
    }
    if (!this.data.formData.visitTime) {
      wx.showToast({
        title: '请选择预约时间',
        icon: "none"
      })
      return
    }
    this.setData({
      'formData.introUserId': this.data.introUserId || '111',
      'formData.introName': '不知名',
      'formData.introPhone': this.data.introPhone || '19989898989'
    })

    this.createAppointRecordAction();
  },
  //创建预约
  createAppointRecordAction() {
    wx.showLoading();
    createAppointRecord(this.data.formData).then(res => {
      wx.hideLoading();
      if (res.code == 200) {
        wx.showToast({
          title: '预约成功!',
          icon: "success"
        })
      }

    }).catch(err => {
      wx.hideLoading();
    })
  },
  closePosterPop() {
    this.setData({
      isShowPosterPop: false,
    })
  },
  //生成分享海报
  createPoster() {
    if (!this.data.isLogin) {
      wx.navigateTo({
        url: '/pages/login/login',
      })
      return;
    }
    if (this.data.posterImg) {
      this.setData({
        isShowSharePop: false,
        isShowPosterPop: true,
      })
      return;
    }
    wx.showLoading({
      title: '海报生成中...',
    })
    this.configPosterView();
  },
  //配置海报
  configPosterView() {
    //头像:
    // let userAvatar = 'posterViews[' + 1 + '].url';
    // //昵称:
    // let userName = 'posterViews[' + 2 + '].text';
    //封面图:
    let houseCover = 'posterViews[' + 1 + '].url';
    //价格
    // let goodPrice = 'posterViews[' +  + '].text';
    // 商品名称
    let goodName = 'posterViews[' + 6 + '].text';
    // 商品名称1
    let goodNameTwo = 'posterViews[' + 7 + '].text';
    // //二维码:
    let qrCode = 'posterViews[' + 4 + '].url';
    let address = 'posterViews[' + 8 + '].text';

    // let storeName = this.data.productDetail.storeName;
    // let storeNameOne = "";
    // let storeNameTwo = "";
    // if (storeName.length > 13) {
    //   storeNameOne = storeName.substring(0, 14);
    //   storeNameTwo = storeName.substring(14, storeName.length);
    //   if (storeNameTwo.length > 12) {
    //     storeNameTwo = storeNameTwo.substring(0, 12) + "..."
    //   }
    // } else {
    //   storeNameOne = storeName;
    //   storeNameTwo = ""
    // }


    this.setData({
      // [userAvatar]: "",
      // [userName]: "张三",
      [houseCover]: "https://images.jiabao19.com/home/lllll.png",
      // [goodPrice]: "￥" + this.data.productDetail.price,
      // [goodPrice]: '',
      [goodName]: "赖老师 19828641431",
      [goodNameTwo]: "蒋老师 13330931790",
      [qrCode]: this.data.productQrCode,
      [address]: '成铁建广场佳宝视力防控养护中心'
    })
    this.setData({
      'posterData.views': this.data.posterViews,
      posterInfo: this.data.posterData
    })
  },
  //保存海报到本地
  savePosterToLocal() {
    if (!this.data.posterImg) {
      wx.showToast({
        title: '暂无可保存海报图片',
        icon: "none"
      })
      return;
    }
    let that = this;
    wx.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success: () => {
              // 同意授权
              //保存到本地
              wx.saveImageToPhotosAlbum({
                filePath: this.data.posterImg,
                success(res) {
                  wx.showToast({
                    title: '保存海报成功',
                    icon: 'success',
                    duration: 2000
                  })

                },
                fail: (err) => {
                  console.log("JJLog:保存图片失败:" + JSON.stringify(err));
                  wx.showToast({
                    title: '保存海报失败',
                    icon: "none"
                  })
                }
              })
            },
            fail: (res) => {
              console.log(res);
              wx.showModal({
                title: '提示',
                content: '保存图片需要您同意访问您的相册',
                success(res) {
                  if (res.confirm) {
                    wx.openSetting();
                  } else if (res.cancel) {
                    // console.log('用户点击取消')
                  }
                }
              })


            }
          })
        } else {
          // 已经授权了
          //保存到本地
          wx.saveImageToPhotosAlbum({
            filePath: this.data.posterImg,
            success(res) {
              wx.showToast({
                title: '保存海报成功',
                icon: 'success',
                duration: 2000
              })

            },
            fail: (err) => {
              console.log("JJLog:保存图片失败:" + JSON.stringify(err));
              wx.showToast({
                title: '保存海报失败',
                icon: "none"
              })
            }
          })
        }
      },
      fail: (res) => {
        console.log(res);
      }
    })
  },
  // 点击弹窗弹出预约填写页面
  showPopAction() {
    this.setData({
      showYYPop: true,
    })
    // this.createAppointRecordAction()
  },

  //生成海报成功:
  posterCreateSuccess(e) {
    wx.hideLoading();

    this.setData({
      isShowSharePop: false,
      isShowPosterPop: true,
      posterImg: e.detail.path,
    });

  },
  //生成海报失败:
  posterCreateError() {
    wx.hideLoading();
    wx.showToast({
      title: '生成海报失败',
      icon: "none"
    })
  },
  clickCenterPopupOverlay() {
    this.setData({
      showYYPop: false,
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let path = "";
    path = "/featurePackage/pages/eyeLove/eyeLove?isShare=1" + "&userId=" + this.data.introUserId + "&houseNumber=" + this.data.introPhone

    return {
      title: "佳宝视力防护养控-硒激新生，科训焕明",
      path: path
    }
  },
})